home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 9026 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.0 KB  |  75 lines

  1. Path: surfnet.nl!sun4nl!xs4all!falstaff
  2. From: falstaff@xs4all.nl (Falstaff)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: read/write integers to files
  5. Date: 7 Mar 1996 15:38:16 GMT
  6. Organization: XS4ALL, networking for the masses
  7. Message-ID: <4hmvt8$n5t@news.xs4all.nl>
  8. References: <313EBF65.4E82@www.inia.net.au>
  9. NNTP-Posting-Host: xs1.xs4all.nl
  10. X-Newsreader: NN version 6.5.0 #666 (NOV)
  11.  
  12. Jason Collins <jason@www.inia.net.au> writes:
  13.  
  14. >Hi there,
  15.  
  16. >I would preface this question with the standard "dumb newbie question......." or whatever but I 
  17. >think you'll work it out for yourselves soon enough.
  18.  
  19. >My problem is that I'm trying to write a program that will read an integer from the file 
  20. >count.dat, increment the integer then write it back to count.dat.  I have provided the listing so 
  21. >that you can all tell me what I'm doing wrong.
  22.  
  23. >void main()
  24.  
  25. main() should return an int.
  26.  
  27. >{
  28. >  char ctr;
  29.  
  30. >  filePtr=fopen("count.dat", "ab");
  31.  
  32. Why use file mode "ab"?  Just using "r" would work just fine.
  33.  
  34. >  fscanf(filePtr, "%d", &ctr);
  35.  
  36. Lucky if you're alive after this!  scanf requires the paremter to store the
  37. %d argument in to be an _int_, not a char.
  38.  
  39. >  fclose(filePtr);
  40.  
  41. >  ctr++;
  42.  
  43. >  filePtr=fopen("count.dat", "wb");
  44.  
  45. Why not use mode "w"?
  46.  
  47. >  fprintf(filePtr, "%d", ctr);
  48. >  fclose(filePtr);
  49. >}
  50.  
  51. Also, if you open the file with "r+" mode, you need not close and reopen it,
  52. but can use rewind() on it.  This only works if the new contents are at
  53. least as large as the old, but that's pretty much assured when you're
  54. only incrementing the number (and watch out for overflows).
  55.  
  56. The program then becomes:
  57.  
  58. int main()
  59. {  int ctr;
  60.  
  61.    filePtr=fopen("count.dat","r+");
  62.    fscanf(filePtr,"%d",&ctr);
  63.    rewind(filePtr);
  64.    fprintf(filePtr,"%d",++ctr);
  65.    fclose(filePtr);
  66.  
  67.    return 0;
  68. }
  69.  
  70. Frank
  71. --
  72. The famous GIICM now on line:  http://www.xs4all.nl/~falstaff/GIICM.html
  73. ------------------------------------------------------------------------
  74. Frank A. Vorstenbosch        +31-(70)-355 5241        falstaff@xs4all.nl
  75.